package com.glq.book.servlet;

import com.glq.book.dao.UserDao;
import com.glq.book.entity.User;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 老白
 */
@WebServlet("/uploadImg")
public class UploadServlet extends HttpServlet {

    UserDao adminDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        SmartUpload smartUpload = new SmartUpload();
        ServletConfig config = this.getServletConfig();
        smartUpload.initialize(config, req, resp);
        try {
            smartUpload.upload();
            File smartFile = smartUpload.getFiles().getFile(0);
            String filePath = "D:/myimger/"
                    + smartFile.getFileName();
            smartFile.saveAs(filePath,
                    SmartUpload.SAVE_PHYSICAL);
            adminDao.updateUserTouXiang("/myimger/"+smartFile.getFileName(), username);
            String msg = "Upload Success!";
            resp.sendRedirect("/user?type=userInfo&username=" + username);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "Upload Fail!";
            resp.getWriter().write(msg);
        }

    }
}
